package com.quan.admin.listener;

import com.quan.admin.commons.constant.RabbitMQConstant;
import com.quan.commons.tools.mail.MailTools;
import com.quan.commons.tools.mail.vo.MailBean;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * MQ监听-发送邮件
 */
@Slf4j
@RabbitListener(queues = RabbitMQConstant.SYSTEM_QUEUE_MAIL)
@Service
public class SendMailListener {

    @Autowired
    private MailTools mailTools;


    @RabbitHandler
    public void listener(MailBean mailBean, Channel channel, Message message) throws IOException {
        try {
            log.debug("收到邮件发送消息：{}", mailBean);

            this.mailTools.send(mailBean);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

}
